package com.abhinav;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class MonitorDirectory {
	public static void main(String[] args) throws IOException, InterruptedException {
		Path folder = Paths.get("/temp");
		WatchService watchService = FileSystems.getDefault().newWatchService();
		folder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
				StandardWatchEventKinds.ENTRY_MODIFY);

		boolean valid = true;

		do {
			WatchKey key = watchService.take();
			for (WatchEvent<?> events : key.pollEvents()) {
				WatchEvent.Kind<?> kind = events.kind();

				if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind)) {
					String fileName = events.context().toString();
					System.out.println("File Created:" + fileName);
				}else if(StandardWatchEventKinds.ENTRY_DELETE.equals(kind)){
					String fileName = events.context().toString();
					System.out.println("File Deleted:" + fileName);
				}else if(StandardWatchEventKinds.ENTRY_MODIFY.equals(kind)){
					String fileName = events.context().toString();
					System.out.println("File Modified:" + fileName);
				}
			}
			valid = key.reset();
		} while (valid);
	}
}
